package com.fy.core.filter;

import cn.hutool.json.JSON;
import cn.hutool.json.JSONUtil;
import com.fy.core.context.AuthContext;
import com.fy.core.enums.ApiErrorEnum;
import com.fy.core.util.JWTUtil;
import com.fy.core.vo.ApiRest;
import com.fy.sys.entity.User;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@Component
@Slf4j
/**
 * 校验用户是否登录
 * 校验令牌
 * 合法：放行
 * 不合法：响应客户端用户没登录
 */
public class GlobalAuthFilter extends OncePerRequestFilter {
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {

        if("OPTIONS".equals(request.getMethod())){
            filterChain.doFilter(request,response); //放行
            return;
        }

        //放行登录
        String requestURI = request.getRequestURI();
        if("/user/login".equals(requestURI)||"/captchaImage".equals(requestURI) || "/user/verify".equals(requestURI)){
            filterChain.doFilter(request,response); //放行
            return;
        }

        //从请求头获取token
        String token = request.getHeader("token");
        if(StringUtils.isEmpty(token) || "null".equals(token)){
            responseVlient(response,ApiRest.failure(ApiErrorEnum.LOGIN_TOKEN_IS_EMPTY,""));
            return ;
        }


        User user = JWTUtil.verifyToken(token);
        if (user != null) { //有效令牌
            //将user存放到上下文中
            AuthContext.setUser(user);
            filterChain.doFilter(request,response); //放行
            //业务处理完成，清空上下文(不清-> 内存泄漏-> 内存溢出)
            AuthContext.clear();
            return;
        }else{
            responseVlient(response,ApiRest.failure(ApiErrorEnum.LOGIN_TOKEN_IS_INVALID,""));
            return ;
        }




    }


    private void responseVlient(HttpServletResponse response,ApiRest apiRest){
        response.setContentType("application/json;charset=utf-8");
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
        PrintWriter writer = null;
        try {
            writer = response.getWriter();
        } catch (IOException e) {
            e.printStackTrace();
        }
        writer.write(JSONUtil.toJsonStr(apiRest));

    }
}
